package com.caszx.chargingpile.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.utils.DiskUser;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.DialogFragment;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**
 * 确认充电
 */
public class BatteryScannedActivity extends BaseTopBarNetActivity implements RadioGroup.OnCheckedChangeListener {

    /**
     * 扫描二维码充电
     */
    public static int TITLE_SCANN = 0;
    /**
     * 扫描蓝牙充电
     */
    public static int TITLE_QRCODE = 1;

    private String pileQRCode;

    private int title_code;

    @Override
    protected void init() {
        pileQRCode = getIntent().getStringExtra("CODE");
        title_code = getIntent().getExtras().getInt("TITLE");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        String title = title_code == TITLE_SCANN ? "扫码充电" : "蓝牙充电";
        setCenterTitle(title);
    }

    public void onEvent(String action){
        if(EventBusAction.ACTION_USER_PAY_SUCCESS.equals(action)){
            //付款成功
            finish();
        }
    }
    @Override
    protected void onLoad() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("pileQRCode", pileQRCode);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_SCANNED_CHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if(code==-100){
                                DialogHelp.showDialogOnlyMesg(BatteryScannedActivity.this,getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(BatteryScannedActivity.this,UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                showErrorView(getResources().getString(R.string.error_minus_100));
                                return;
                            }

                            if(code==-550){
                                DialogHelp.showDialogOnlyMesg(BatteryScannedActivity.this,getResources().getString(R.string.error_minus_550), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(BatteryScannedActivity.this,UserBindVipActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                showErrorView(getResources().getString(R.string.error_minus_550));
                                return;
                            }
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                showErrorView(resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    showContentView();
                                    steupContentView(response);
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.activity_battery_scanned, getContentView(), true);
        return view;
    }

    private TextView txt_station_name;
    private TextView txt_station_no;
    private TextView txt_station_state;
    private TextView txt_station_price;
    private TextView txt_station_error;
    private RadioGroup rg_gun;
    private TextView btn;

    private String ordersId;
    private String gunNo;
    private String pileNo;

    private void steupContentView(JSONObject jsonObject) {
        txt_station_name = (TextView) findViewById(R.id.txt_station_name);
        txt_station_no = (TextView) findViewById(R.id.txt_station_no);
        txt_station_state = (TextView) findViewById(R.id.txt_station_state);
        txt_station_price = (TextView) findViewById(R.id.txt_station_price);
        txt_station_error = (TextView) findViewById(R.id.txt_station_error);
        rg_gun = (RadioGroup) findViewById(R.id.rg_gun);
        btn = (TextView) findViewById(R.id.btn);
        rg_gun.setOnCheckedChangeListener(this);

        txt_station_name.setText(jsonObject.optString("stationName"));
        txt_station_no.setText(jsonObject.optString("pileNo"));
        txt_station_state.setText(jsonObject.optString("gunStatusTip"));
        txt_station_state.setText(jsonObject.optString("gunStatusTip"));
        ordersId = jsonObject.optString("ordersId");
        pileNo = jsonObject.optString("pileNo");
//        gunNo = jsonObject.optString("gunNo");
        gunNo = "1";
        if (TextUtils.isEmpty(ordersId)) {
            txt_station_price.setVisibility(View.GONE);
        } else {
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(jsonObject.optString("beforeDate"));
            builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray5)), 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.append("\n");
            builder.append("支付预约费");
            int start = builder.length();
            DecimalFormat decimalFormat = new DecimalFormat("￥###.##");
            builder.append(decimalFormat.format(jsonObject.optDouble("beforeFee")));
            builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)), start, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            txt_station_price.setText(builder);
        }

        SpannableStringBuilder builder_error = new SpannableStringBuilder();

        builder_error.append("如果不能充电\n");
        int start = builder_error.length();
        builder_error.append("请您提交电桩报错信息");
        txt_station_error.setMovementMethod(LinkMovementMethod.getInstance());
        builder_error.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(BatteryScannedActivity.this, ErrorActivity.class);
                intent.putExtra("ID", ordersId);
                startActivity(intent);

            }
        }, start, builder_error.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        builder_error.setSpan(new ForegroundColorSpan(Color.parseColor("#FF032FF1")), start, builder_error.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_station_error.setText(builder_error);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmCharge();
            }
        });
    }

    /**
     * @author eddie
     * @time 2018-11-14 0014  15:17
     * @describe radiogroup checked listener
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId) {
            case R.id.rb_a_gun:
                gunNo = "1";
                break;
            case R.id.rb_b_gun:
                gunNo = "2";
                break;
        }
    }

    /**
     * 确认充电
     */
    private void confirmCharge() {

        showProgressDialog("提交中");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("gunNo", gunNo);//枪的编号
        params.put("ordersId", ordersId);
        params.put("pileNo", pileNo);//桩的编号
        OkHttpUtils.post()
                .url(ConstantUrl.URL_CONFIRM_CHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this, getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if(code==-100){
                                DialogHelp.showDialogOnlyMesg(BatteryScannedActivity.this,getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(BatteryScannedActivity.this,UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                return;
                            }
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                if (code == -550) {
                                    String id = response.optString("ordersId");
                                    getChargePrice(id);
                                } else {
                                    SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this, resultJsonObject.optString("msg"));
                                }
                            } else {
                                try {
                                    String ordersId = response.optString("ordersId");
                                    Intent intent = new Intent(BatteryScannedActivity.this, BatteryChargeActivity.class);
                                    intent.putExtra("ID", ordersId);
                                    startActivity(intent);
                                    finish();
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this, getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 得到充电的费用
     */
    private void getChargePrice(String id) {
        showProgressDialog("获取未支付订单");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("ordersId", id);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_ORDERS_DETAIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this,getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this, resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    Intent intent = new Intent(BatteryScannedActivity.this, PayActivity.class);
                                    //充电的订单号
                                    intent.putExtra("ordersId", response.optString("ordersId"));
                                    //电站名称
                                    intent.putExtra("stationName", response.optString("stationName"));
                                    //时长
                                    intent.putExtra("timeLong", response.optLong("timeLong"));
                                    //时间段
                                    intent.putExtra("timeSlot", response.optString("timeSlot"));
                                    //用电量
                                    intent.putExtra("changePower", response.optDouble("changePower"));
                                    //充电费用
                                    intent.putExtra("chargeFees", response.optDouble("chargeFees"));
                                    //服务费
                                    intent.putExtra("serverFees", response.optDouble("serverFees"));
                                    //停车费
                                    intent.putExtra("stopFees", response.optDouble("stopFees"));
                                    //总费用
                                    intent.putExtra("totalFees", response.optDouble("totalFees"));
                                    startActivity(intent);
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(BatteryScannedActivity.this, getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
